package com.tbit.uqbike.client.controller;

import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.service.ActiveStatService;
import com.tbit.uqbike.client.service.RedisService;
import com.tbit.uqbike.client.service.TokenService;
import com.tbit.uqbike.client.util.Assert;
import com.tbit.uqbike.client.util.OutputUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.tbit.uqbike.client.constant.RedisConstant.*;

/**
 * 用户活动参与
 *
 * @Author: chen
 * @Description: 用户活动参与
 * @Date: 创建于 9:08 2022/5/12
 */
@Controller
@RequestMapping("activeStat")
public class ActiveStatController {

    @Autowired
    private ActiveStatService activeStatService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisService redisService;



    /**
     * 添加
     *
     * @param token    令牌
     * @param eventId  标识符
     * @param type     类型 0用户分享，1用户查看，2用户接受，3用户完成
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/add")
    public void add(String token, Integer eventId, @RequestParam(defaultValue = "0") Integer type, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            /* 校验 */
            Assert.notNull(eventId, "-3050", "区域id不能为空");
            User user = tokenService.getUser(token);
            dealInviteNewStat(eventId,type,user);
            activeStatService.add(user, eventId, type);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 统计邀新活动数据
     * @param eventId
     * @param type
     * @param user
     */
    private void dealInviteNewStat(Integer eventId, Integer type,User user){
        // 分享
        if (Objects.equals(type,0)){
            redisService.hash_incr(getInviteNewRedisKey(eventId, user.getPhone(), user.getName()), SHARE, 1L);
        }
        // 曝光
        if (Objects.equals(type,1)){
            redisService.hash_incr(getInviteNewRedisKey(eventId, user.getPhone(), user.getName()), EXPOSURE, 1L);
        }
    }

    /**
     * 邀新活动key
     * @param eventId
     * @param phone
     * @param name
     * @return
     */
    private String getInviteNewRedisKey(Integer eventId,String phone,String name){
        return String.format(INVITE_NEW, eventId,phone,name);
    }
}
